import os

import MSConfig; MSConfig.init('.')
initRequired    = True
documentHead    = None
documentFoot    = None
def init():
    global initRequired
    global documentHead
    global documentFoot

    f = open(MSConfig.config.get('main', 'html') + 'head.html', 'r')
    documentHead = [f.read()]
    f = open(MSConfig.config.get('main', 'html') + 'foot.html', 'r')
    documentFoot = [f.read()]
    initRequired = False

## PATTERN FUNCTIONS TO DISPLAY PAGE ##
def putHeader(functor, status, content, mimetype, extra = []):
    statuses =  {
                200: '200 OK',
                400: '400 Bad Request',
                404: '404 Not Found',
                }
    s = statuses.get(status, statuses[400])
    functor(s, [('Content-Type', mimetype + '/' + content)] + extra)

def get404(functor, name):
    putHeader(functor, 404, 'html', 'text')
    return ['<h3>page ' + name + ' not found</h3>']

def getHead():
    global initRequired
    if initRequired: init()
    return documentHead
def getFoot(): 
    global initRequired
    if initRequired: init()
    return documentFoot

# OBJECT PATTERNS #

class PatternTable:
    def __init__(self, classname=None, idname=None, bodyname=None):
        self.classname  = classname
        self.idname     = idname
        self.bodyname   = bodyname

    def open(self, meta):
        tag =   '<table '
        if self.classname:   tag += 'class="%s" ' % str(self.classname)
        if self.idname:      tag += 'id="%s" ' % str(self.idname)
        tag +=  '>'
        tag +=  '<thead><tr>'
        columnCount = 0
        for name, desc in meta:
            c =     '<th '
            for propname, propval in desc.iteritems():
                c += '%s="%s" ' % (str(propname), str(propval))
            c +=    '>' + str(name) + '</th>'
            tag += c
            columnCount += 1
        self.columnCount = columnCount
        tag +=  '</tr></thead>'
        tag +=  '<tbody '
        if self.bodyname: tag += 'class="%s" id="%s"' % (str(self.bodyname), str(self.bodyname))
        tag +=  '>'
        return [tag]
    def close(self):
        tag = '</tbody></table>'
        return [tag]
    def add(self, e):
        tag =   '<tr>'
        for i in range(0, self.columnCount): tag += '<th>' + str(e[i]) + '</th>'
        tag +=  '</tr>'
        return [tag]

class PatternElement:
    def __init__(self, name, etype, desc):
        self.name = name
        self.desc = desc
        self.etype = etype

    def open(self, meta, value='', closetag=False, hidden=False):
        tag = '<div class="clearfix" '
        if hidden: tag += 'hidden="true" '
        tag += '>'
        tag += '<label for="%s">%s</label>' % (self.name, self.desc)
        tag += '<div class="%s">' % self.etype
        tag += '<%s ' % self.etype
        for pname, pval in meta.iteritems():
            tag += '%s="%s"' % (str(pname), str(pval))
        tag += '>'
        if closetag: tag += value + '</%s>' % self.etype
        tag += '</div>'
        tag += '</div>'
        return [tag]

class PatternForm:
    def __init__(self, action, button, method):
        self.action = '/method/' + action
        self.method = method
        self.target = '_blank'
        self.button = button

    def open(self, meta, extra=''):
        tag =   '<form action=%s target=%s method=%s>' % (self.action, self.target, self.method)
        for k, v in meta.iteritems():
            t = PatternElement(k, v['type'], v['desc'])
            tag += t.open(v['meta'], v['value'], v['closetag'], v['hidden'])[0]

        tag += extra
        tag +=  '<button class="btn primary" type="submit">%s</button>' % self.button
        tag +=  '</form>'
        return [tag]


## PATTERN FUNCTIONS TO HANDLE USER DATA ##
def checkName(name):
    if name and type(name) == type(str()) and len(name) >= 4 and name.find('..') == -1: return True
    return False
def checkFile(name):
    if os.path.exists(name): return True
    return False
